// 个人中心，更换手机号，原手机号获取验证码
$('#getCode').click(function () {
    setCodeTime(this, $('#telOld').text());
});

/**
 *  初始化手机验证码的倒计时间
 * @param el       点击获取的class，如，'.new-check'
 * @param phoneNum 手机号
 */
function setCodeTime(el, phoneNum) {
    var time = 60;
    $(el).html("<b>" + time + "</b>秒");
    setTime(time, el);
    // sendPhoneVertificationCode(phoneNum);
}

/**
 *  手机验证码倒计时
 * @param time 剩余时间
 * @param el   时间标签
 */
function setTime(time, el) {
    var interval = setInterval(function () {
        $('b', $(el)).text(--time);
        if (time < 1) {
            $(el).html('重新获取');
            clearInterval(interval);
        }
    }, 1000);
}

/**
 *  textarea高度自适应
 *  调用autoTextarea($('#textarea')[0]);
 *    @param elem js方式获取到的元素
 *  @param extra 额外增加的高度
 */
function autoTextarea(elem, extra, maxHeight) {
    extra = extra || 0;
    var isFirefox = !!document.getBoxObjectFor || 'mozInnerScreenX' in window,
        isOpera = !!window.opera && !!window.opera.toString().indexOf('Opera'),
        addEvent = function (type, callback) {
            elem.addEventListener ?
                elem.addEventListener(type, callback, false) :
                elem.attachEvent('on' + type, callback);
        },
        getStyle = elem.currentStyle ? function (name) {
            var val = elem.currentStyle[name];
            if (name === 'height' && val.search(/px/i) !== 1) {
                var rect = elem.getBoundingClientRect();
                return rect.bottom - rect.top -
                    parseFloat(getStyle('paddingTop')) -
                    parseFloat(getStyle('paddingBottom')) + 'px';
            }
            ;
            return val;
        } : function (name) {
            return getComputedStyle(elem, null)[name];
        },
        minHeight = parseFloat(getStyle('height'));
    elem.style.resize = 'none';
    var change = function () {
        var scrollTop, height,
            padding = 0,
            style = elem.style;
        if (elem._length === elem.value.length) return;
        elem._length = elem.value.length;
        if (!isFirefox && !isOpera) {
            padding = parseInt(getStyle('paddingTop')) + parseInt(getStyle('paddingBottom'));
        }
        ;
        scrollTop = document.body.scrollTop || document.documentElement.scrollTop;
        elem.style.height = minHeight + 'px';
        if (elem.scrollHeight > minHeight) {
            if (maxHeight && elem.scrollHeight > maxHeight) {
                height = maxHeight - padding;
                style.overflowY = 'auto';
            } else {
                height = elem.scrollHeight - padding;
                style.overflowY = 'hidden';
            }
            ;
            style.height = height + extra + 'px';
            scrollTop += parseInt(style.height) - elem.currHeight;
            document.body.scrollTop = scrollTop;
            document.documentElement.scrollTop = scrollTop;
            elem.currHeight = parseInt(style.height);
        }
        ;
    };
    addEvent('propertychange', change);
    addEvent('input', change);
    addEvent('focus', change);
    change();
};

/**
 * 登录窗口
 * @param f 登录后的回调方法
 */
function toLogin(f) {
    layui.use(['form', 'layer'], function () {
        var form = layui.form,
            layer = layui.layer,
            $ = layui.jquery;
        layer.open({
            type: 1,
            id: 'layerDemoLogin' //防止重复弹出
            , title: '用户登录'
            , area: ['300px', '285px']
            , content: '<form class="layui-form" >' +
            '<div class="layui-form-item">' +
            '<i class="glyphicon glyphicon-user"></i>' +
            '<input type="text" name="account" lay-verify="required" autofocus autocomplete="off" placeholder="请输入用户名" class="layui-input paddingLeft">' +
            '</div><div class="layui-form-item">' +
            '<i class="glyphicon glyphicon-lock"></i>' +
            '<input  type="password" name="password" lay-verify="required" autocomplete="off" placeholder="请输入密码" class="layui-input paddingLeft">' +
            '</div><div class="layui-form-item">' +
            '<div class="layui-input-inline" style="width:40%">' +
            '<input  type="password" name="code" lay-verify="required" autocomplete="off" placeholder="请输入验证码" class="layui-input">' +
            '</div><div class="layui-input-inline"  style="width:40%">' +
            '<img onclick="setUrl(this)" src="' + getRootPath().projectName + '/validatecode/" />' +
            '</div>' +
            '</div><div class="layui-form-item">' +
            '<a id="submit003" class="layui-btn" lay-submit=""  lay-filter="formDemo222">立即提交</a>' +
            '</div>' +
            '</form>'
            , shade: 0.8 //不显示遮罩
            , zIndex: layer.zIndex //重点1
            , btn: false
            , offset: 'auto'
        });
        // 监听立即提交
        form.on('submit(formDemo222)', function (data) {
            //登录成功后执行传入的方法
            $.ajax({
                url: WebContext + "/hr/getByAccountAndPassword",
                data: data.field,
                type: "post",
                dataType: "json",
                success: function (data) {
                    if (data.success == true) {
                        if (typeof f == "function") {
                            layer.closeAll();
                            f();
                        } else {
                            //传入的方法有误
                        }
                    } else {
                        loading(1);
                        setUrl($("#img")[0]);
                        alert(data.error)
                    }
                }
            });
        });

    });
    $(document).on('keydown', function (e) {
        if (e.keyCode == 13) {
            $("#submit003").click();
        }
    });


}

function login(data) {
    loading();
    $.ajax({
        url: WebContext + "/muser/login",
        data: data,
        type: "post",
        dataType: "json",
        success: function (data) {
            if (data.success == true) {
                if (location.href.indexOf("index.html") != -1) {
                    location.reload();
                } else {
                    location.href = WebContext + "/static/ms/html/index.html";
                }
            } else {
                loading(1);
                setUrl($("#img")[0]);
                alert(data.error)
            }

        }
    });


}

function setUrl(el) {
    el.src = getRootPath().projectName + "/validatecode/?" + Math.random();
}

/**
 *  加载动画
 * @param num 不传值或0：加载中；1：加载完
 */
var index;

function loading(num) {
    layui.use(['form', 'element', 'util', 'layedit', 'laydate', 'laypage', 'layer'], function () {
        var layer = layui.layer;
        num = num || 0;
        if (num == 0) {
            index = layer.load(2);
        } else {
            layer.closeAll();
        }
    });
}

/**
 * 替换a标签的href属性,始其可以新打开一页
 */
function aTagReplace(n, title) {

    var url = $(n).attr("href");
    title = title || null;
    if (url != "undefined") {
        $(n).removeAttr("href");
        $(n).removeAttr("onclick");
        $(n).on("click", function () {
            PEMS.proxyAjax(function () {
                    addIframeFromSub($(n), WebContext + url, title, false);
                }
            );

        });
        PEMS.proxyAjax(function () {
            addIframeFromSub($(n), WebContext + url, title, false);
        });

    }


}

/**
 * Created by wenwenLi on 2018-01-22.
 */

//==================================hplus 插件相关方法开始=======================

/**
 *  增加iframe，在子页面调用
 * @param el 触发该事件的元素
 * @param href 新页面对应的url
 * @param title 新页面的title值,为空时对应html页面的title属性
 * @param isClose   默认为false，跳转的href的页面存在时，是否关闭重开，true为是，false为直接选中
 * @returns {boolean}
 */
function addIframeFromSub(el, href, title, isClose) {
    try {
        var wind = getIframeWindowByContent(title);
        wind.location.reload();
        wind.show();
    } catch (e) {
        var $this = $(el);
        var o = href,
            m = new Date().getTime(),
            l = title || $.trim($this.text()),
            k = true;
        var isClose = isClose || false;

        if (o == undefined || $.trim(o).length == 0) {
            return false
        }//  o：新增页的url，m：index，l：text
        $(".J_menuTab", parent.document).each(function () {//.J_menuTab 右侧-标题关闭栏
            if ($(this).data("id") == o) {// 判断右侧内容区，是否加了对应的iframe
                if (isClose) {
                    var $closeEl = getITagByContent(l);
                    parent.closeByBtnInSubPage($closeEl);
                    k = true;
                } else {

                    if (!$(this).hasClass("active")) {// 右侧-标题关闭栏-选中
                        $(this).addClass("active").siblings(".J_menuTab").removeClass("active");
                        $(".J_mainContent .J_iframe", parent.document).each(function () {// 右侧-主内容区，显示相应的iframe，其他iframe，hide
                            if ($(this).data("id") == o) {
                                $(this).show().siblings(".J_iframe").hide();
                                return false;
                            }
                        })
                    }
                    k = false;
                }
                return false
            }
        });
        if (k) {
            var p = '<a href="javascript:;" class="active J_menuTab" data-id="' + o + '">' + l + ' <i class="fa fa-times-circle"></i></a>';
            $(".J_menuTab", parent.document).removeClass("active");
            var n = '<iframe class="J_iframe" name="iframe' + m + '" width="100%" height="100%" src="' + o + '" frameborder="0" data-id="' + o + '" seamless></iframe>';
            $(".J_mainContent", parent.document).find("iframe.J_iframe").hide().parents(".J_mainContent").append(n);
            $(".J_menuTabs .page-tabs-content", parent.document).append(p);

        }
    }

    return false
}

/**
 * 根据页签内容获得页签
 * @param content
 * @returns {*|{}|jQuery}
 */
function getITagByContent(content, cycle) {
    cycle = (cycle ? cycle : parent.document);
    var arr = $("a.J_menuTab", cycle)
    var target;
    $.each(arr, function (index, node) {
        if ($(node).text().indexOf(content) != -1) {
            target = node;
        }
    });
    var i = $(target).find("i");
    if (i.length == 0) {
        return $(target);
    } else {
        return i;
    }
}

function showTable(lable) {
    $(".J_menuTab", parent.document).each(function () {
        if ($(this).html().indexOf(lable) != -1) {
            if (!$(this).hasClass("active")) {
                $(this).addClass("active").siblings(".J_menuTab").removeClass("active");
                var src = $(this).attr("data-id");
                $(".J_mainContent .J_iframe", parent.document).each(function () {
                    if ($(this).attr("data-id") == src) {
                        $(this).show().siblings(".J_iframe").hide();
                    }
                })
            }
        }
    });
}

/**
 * 获取url传递的参数
 */
function getQueryParamsAndValuesFromUrl() {
    var name, value;
    var str = location.href;
    var num = str.indexOf("?");
    str = str.substr(num + 1);
    var result = {};
    var arr = str.split("&"); //各个参数放到数组里
    for (var i = 0; i < arr.length; i++) {
        num = arr[i].indexOf("=");
        if (num > 0) {
            name = arr[i].substring(0, num);
            value = arr[i].substr(num + 1);
            result[name] = value;
        }
    }
    return result;
}

function closeByBtnInSubPage($el) {
    var $this = $el;
    var m = $this.parents(".J_menuTab").data("id");
    var l = $this.parents(".J_menuTab").width();
    if ($this.parents(".J_menuTab").hasClass("active")) {
        if ($this.parents(".J_menuTab").next(".J_menuTab").size()) {
            var k = $this.parents(".J_menuTab").next(".J_menuTab:eq(0)").data("id");
            $this.parents(".J_menuTab").next(".J_menuTab:eq(0)").addClass("active");
            $(".J_mainContent .J_iframe", parent.document).each(function () {
                if ($(this).data("id") == k) {
                    $(this).show().siblings(".J_iframe").hide();
                    return false
                }
            });
            var n = parseInt($(".page-tabs-content", parent.document).css("margin-left"));
            if (n < 0) {
                $(".page-tabs-content", parent.document).animate({
                        marginLeft: (n + l) + "px"
                    },
                    "fast")
            }
            $this.parents(".J_menuTab").remove();
            $(".J_mainContent .J_iframe", parent.document).each(function () {
                if ($(this).data("id") == m) {
                    $(this).remove();
                    return false
                }
            })
        }

        if ($this.parents(".J_menuTab").prev(".J_menuTab").size()) {
            var k = $this.parents(".J_menuTab").prev(".J_menuTab:last").data("id");
            $this.parents(".J_menuTab").prev(".J_menuTab:last").addClass("active");
            $(".J_mainContent .J_iframe", parent.document).each(function () {
                if ($(this).data("id") == k) {
                    $(this).show().siblings(".J_iframe").hide();
                    return false
                }
            });
            $this.parents(".J_menuTab").remove();
            $(".J_mainContent .J_iframe", parent.document).each(function () {
                if ($(this).data("id") == m) {
                    $(this).remove();
                    return false
                }
            })
        }
    } else {
        $this.parents(".J_menuTab").remove();
        $(".J_mainContent .J_iframe", parent.document).each(function () {
            if ($(this).data("id") == m) {
                $(this).remove();
                return false
            }
        });
        g($(".J_menuTab.active"))
    }
    return false
}


function getIframeWindowByContent(content) {
    var arr = $("a.J_menuTab", parent.document)
    var target;
    $.each(arr, function (index, node) {
        if ($(node).text().indexOf(content) != -1) {
            target = node;
        }
    });
    var data_id = $(target).attr("data-id");
    var targetIframe;

    var iframes = top.document.getElementsByTagName("iframe");
    $.each(iframes, function (i, n) {
        if ($(n).attr("data-id") == data_id) {
            targetIframe = n;
        }
    });
    showTable("资源池");
    if (targetIframe != null) {
        return targetIframe.contentWindow;
    }
}

//=================================hplus 相关方法结束=======================================

//================================
/**
 * 格式化日期为"yyyy-MM-dd hh:mm:ss"格式
 * @param format 待格式化的值
 * @returns {*}
 */
Date.prototype.format = function (format) {
    /*
     * eg:format="yyyy-MM-dd hh:mm:ss";
     */
    var o = {
        "M+": this.getMonth() + 1, // month
        "d+": this.getDate(), // day
        "h+": this.getHours(), // hour
        "m+": this.getMinutes(), // minute
        "s+": this.getSeconds(), // second
        "q+": Math.floor((this.getMonth() + 3) / 3), // quarter
        "S": this.getMilliseconds()
        // millisecond
    };

    if (/(y+)/.test(format)) {
        format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4
            - RegExp.$1.length));
    }

    for (var k in o) {
        if (new RegExp("(" + k + ")").test(format)) {
            format = format.replace(RegExp.$1, RegExp.$1.length == 1
                ? o[k]
                : ("00" + o[k]).substr(("" + o[k]).length));
        }
    }
    return format;
};

function dateTimeFormatter(vale, row, index) {
    return PEMS.formateDate(vale, "yyyy-MM-dd");
}

var PEMS = function ($, window, document) {
    /**
     * 格式化日期
     * @param value
     * @param pattern
     * @returns {*}
     */
    function formateDate(value, pattern) {
        if (pattern != null && pattern != "undefined") {
            return new Date(value).format(pattern);
        } else {
            return new Date(value).format("yyyy-MM-dd hh:mm:ss");
        }
    }

    /**
     * 校验有没有登录
     * @returns {boolean}
     */
    function checkLogin() {
        var f;
        $.ajax({
            url: WebContext + "/muser/checkLogin",
            type: "post",
            async: false,
            dataType: "json",
            success: function (data) {
                if (data.success == true) {
                    f = true;
                } else {
                    f = false;
                }
            }
        });
        return true;
    }

    return {
        proxyAjax: function (f) {
            if (checkLogin() == true) {
                f();
            } else {
                toLogin(f);
            }
        },
        formateDate: function (value, pattern) {
            return formateDate(value, pattern);
        },
        openInFoWindow: function (title, content, f) {
            layui.use("layer", function () {
                layer.open({
                    id: new Date().getTime(),
                    title: "提示信息",
                    type: 1,
                    content: '<div style="width: 300px;height:100px;text-align: center;line-height: 100px" >' + content + '</div>',
                    btn: ['确认', '取消'],
                    btnAlign: "c",
                    yes: function () {
                        f();
                    }
                });
            });
        }
    }

}($, window, document);
var WebContext;
$(function () {
    WebContext = getRootPath().projectName;
    localStorage.setItem("WebContext", WebContext);
});

/**
 * 获取项目路径信息
 * @returns {{localhostPath: string, projectName: string}}
 */
function getRootPath() {
    var curWwwPath = window.document.location.href;
    var pathName = window.document.location.pathname;
    var pos = curWwwPath.indexOf(pathName);
    var localhostPath = curWwwPath.substring(0, pos);
    var projectName = pathName.substring(0, pathName.substr(1).indexOf('/') + 1);
    return {
        localhostPath: localhostPath,
        projectName: ""
    }
}

/**
 * 刷新boothstrap -table
 * @param id bootstrap 表格所在的id
 * @param opt 需要传向后台的参数对象
 * @param flage 是否携带页码,默认不携带，true 携带 false 不携带
 * @param f 回调函数
 */
function tableRefresh(id, flage, f, opt) {
    flage = flage || false;
    if (flage) {
        $("#" + id).bootstrapTable("refresh", opt);
    } else {
        $("#" + id).bootstrapTable("emptyTable");
        f();
    }
    try {
        setTimeout(function () {
            bindClick();
        }, 1000);

    } catch (e) {

    }
}

function bindClick() {
    var eles = $(".login-check");
    $.each(eles, function (index, node) {
        var method = $(node).attr("onclick");
        $(node).removeAttr("onclick");
        node.addEventListener("click", function () {
            PEMS.proxyAjax(function () {
                eval(method);
            });
        });
    });
}

function getStrLength(str) {
    return str.replace(/[\u0391-\uFFE5]/g, "aa").length;
}

/**
 *  初始化zTree
 */
function initZtree(url, f) {
    var setting = {
        check: {
            enable: true
        },
        data: {
            simpleData: {
                enable: true
            }
        }
    };
    $.ajax({
        url: WebContext + url,
        type: "post",
        dataType: "json",
        success: function (data) {
            $.fn.zTree.init($("#tree"), setting, data);
            if (typeof f == "function") {
                f();
            }

        }
    });
    /* var zNodes =[
         { id:1, pId:0, name:"随意勾选 1", open:true},
         { id:114, pId:1, name:"随意勾选 1-1"},
         { id:124, pId:1, name:"随意勾选 1-2"},
         { id:2, pId:0, name:"随意勾选 2", open:true},
         { id:21, pId:2, name:"随意勾选 2-1"},
         { id:22, pId:2, name:"随意勾选 2-2"},
         { id:23, pId:2, name:"随意勾选 2-3"}
     ];*/

}

/**
 *  通过id选中zTree节点
 * @param checkdNodes 节点id，数组
 * @param isChecked 不传值为true，选中，传false为取消选中
 * @param isDisabled 不传值为false-不禁用，禁用传true
 */
function checkNodeById(checkdNodes, isChecked, isDisabled) {
    isChecked = isChecked == null ? true : isChecked;
    isDisabled = isDisabled == null ? false : isDisabled;
    var treeObj = $.fn.zTree.getZTreeObj("tree");
    for (var i = 0; i < checkdNodes.length; i++) {
        var treenode = treeObj.getNodeByParam("id", checkdNodes[i], null);
        treeObj.expandNode(treenode, true, true, true);
        if (isDisabled === true) {
            treeObj.setChkDisabled(treenode, false);
            treeObj.checkNode(treenode, isChecked, true);
            treeObj.setChkDisabled(treenode, true);
        }
        var childrenLen = treenode.children ? treenode.children.length : 0;
        if (treenode['pId'] == null && childrenLen > 0) {
            //treeObj.checkNode(treenode, isChecked, true);
        } else {
            if (isDisabled === true) {
                /*treeObj.setChkDisabled(treenode, false);
                treeObj.checkNode(treenode, isChecked, true);
                treeObj.setChkDisabled(treenode, true);*/
            } else {
                treeObj.checkNode(treenode, isChecked, true);
            }
        }
    }
}

/**
 *  通过选中的节点返回节点id，返回数组
 * @returns {Array} 返回节点id
 */
function getIdByCheckedNode() {
    var treeObj = $.fn.zTree.getZTreeObj("tree");
    var nodes = treeObj.getCheckedNodes(true);
    var nodesId = [];
    for (var i = 0; i < nodes.length; i++) {
        nodesId.push(nodes[i]["id"]);
    }
    return nodesId;
}

/**
 *  给所有的z-tree节点设置为disabled
 */
function setDisabledAllNodes(checked) {
    var treeObj = $.fn.zTree.getZTreeObj("tree");
    var nodes = treeObj.getNodes();
    nodes.forEach(function (value) {

        if (checked == true) {
            treeObj.checkNode(value);
        }
        treeObj.setChkDisabled(value, true);
        if (value.hasOwnProperty('children')) {
            value.children.forEach(function (children) {
                if (checked == true) {
                    treeObj.checkNode(children);
                }
                treeObj.setChkDisabled(children, true);
            })
        }
    });
}


/**
 *
 * @param f不能更改供应商执行的方法
 * @param fu 能更改供应商执行的方法
 */
function getCanSelectSupplier(f, fu) {
    $.ajax({
        url: WebContext + "/hr/canSelectSupplier",
        type: "post",
        dataType: "json",
        async: false,
        success: function (data) {
            if (!data) {
                if (typeof f == "function") {
                    f();
                }
            } else {
                if (typeof fu == "function") {
                    fu();
                }
            }
        }
    })
}

/**
 *  下一步,上一步，切换
 * @param index 0为下一步，1为上一步
 */
function toggleStep(index) {
    index = index || 0;
    var $infoWrap = $('.animation-wrap');
    if (index == 0) {
        $infoWrap.eq(index).removeClass('fadeInLeft').addClass('fadeOutLeft').siblings().removeClass('fadeOutRight').addClass('fadeInRight');
    } else {
        $infoWrap.eq(index).removeClass('fadeInRight').addClass('fadeOutRight').siblings().removeClass('fadeOutLeft').addClass('fadeInLeft');
    }
}